package br.com.sgpv2.hibernate.folha;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import br.com.sgpv2.entity.folha.Folha;
import br.com.sgpv2.entity.folha.StatusFolhaEnum;
import br.com.sgpv2.hibernate.infra.SGPGenericDAO;


@Repository(value="folhaRepository")
public class FolhaHibernateDAO extends SGPGenericDAO<Folha> implements FolhaRepository{
	
	@Autowired
	public FolhaHibernateDAO(
			@Qualifier("sessionFactory") SessionFactory factory) {
		super(Folha.class);
		super.setSessionFactory(factory);
	}
	
	public Session recuperarSession(){
		return super.getSession();
	}

	public Folha buscarPorMesAno(Integer mes, Integer ano) {
		Criteria criteria = createCriteria(Folha.class);
		criteria.add(Restrictions.eq("mes", mes));
		criteria.add(Restrictions.eq("ano", ano));

		return (Folha) criteria.uniqueResult();
	}
	
	public int buscarIdPorMesAno(Integer mes, Integer ano) {
		Criteria criteria = createCriteria(Folha.class);
		criteria.add(Restrictions.eq("mes", mes));
		criteria.add(Restrictions.eq("ano", ano));
		criteria.setProjection(
				Projections
						.projectionList()
						.add(Projections.property("id")));

		return (Integer) criteria.uniqueResult();
	}
	
	public List<Folha> consultarFolhaFechada() {
		Criteria criteria = createCriteria(Folha.class);
		criteria.add(Restrictions.eq("status", StatusFolhaEnum.FECHADA));
		criteria.addOrder(Order.desc("ano"));
		criteria.addOrder(Order.desc("mes"));
		return criteria.list();
	}
	
	public List<Folha> consultarFolhas() {
		Criteria criteria = createCriteria(Folha.class);
		criteria.addOrder(Order.desc("ano"));
		criteria.addOrder(Order.desc("mes"));
		return criteria.list();
	}
}
